package com.dap.service.impl;

import com.dap.pojo.Result;
import com.dap.service.ParameterService;
/*import com.dap.utils.SpringDataRedisUtils;*/
import com.dap.utils.SpringDataRedisUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

@Service
public class ParameterServiceImpl implements ParameterService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SpringDataRedisUtils springDataRedisUtils;

    @Override
    public Result setParameter(String json) {
        ObjectMapper om = new ObjectMapper();
        Result result = new Result();
        result.setFlag(true);
        result.setMessage("success");

        try {
            HashMap<String, String> map = om.readValue(json, HashMap.class);
            String key = (String) map.remove("key");

            Set<String> set = map.keySet();
            Iterator<String> iterator = set.iterator();
            while (iterator.hasNext()) {
                String next = iterator.next();
                if (map.get(next) == null || map.get(next) == "") {
                    map.remove(next);
                    set = map.keySet();
                    iterator = set.iterator();

                }
            }

            redisTemplate.opsForHash().putAll(key, map);

        } catch (IOException e) {
            e.printStackTrace();
            result.setFlag(false);
            result.setMessage("failed");
        }

        return result;
    }

    @Override
    public String get(String key) {

        String  value = (String) redisTemplate.opsForValue().get(key);

        return value;
    }

    @Override
    public String get(String key, String filed) {
        String value = (String) redisTemplate.opsForHash().get(key, filed);
        return value;
    }


    @Override
    public Boolean del(String key) {

        try {
            redisTemplate.opsForValue().set(key,null);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;

    }


    @Override
    public Boolean add(String key, String filed, String value) {
        try {
            redisTemplate.opsForHash().put(key,filed,value);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        return true;

    }


    @Override
    public Boolean add(String key, String value) {
        try {
            redisTemplate.opsForValue().set(key,value);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


}
